<?php


class u2s {

    var $api = 'http://u2s.biz';
    
    var $agent = null;
    var $format = 'json';

    function u2s()
    {
        $this->agent = new Snoopy;
        $this->agent->curl_path = '/usr/bin/curl';
        
        $this->agent->user = 'u2s';
        $this->agent->pass = 'u2s';
    }
    
    /**
     * 获得当前的版本
     *
     */
    function get_version()
    {
        $api = $this->api.'/api/statusnet/version.'.$this->format;
        $this->agent->fetch($api);
        return $this->__response2array($this->agent->results);
    }
    
    /**
     * 获得当前的版本
     *
     */
    function status($text, $media=null)
    {
        $api = $this->api.'/api/statuses/update.'.$this->format;
        
        // statusnet使用的#号前面需要有空格
        $text = preg_replace('/(#[^#]+?)#/', ' $1 ', $text);
        $text = mb_strimwidth($text, 0, 137, '...', 'utf-8');
        
        $pars = array(
            'status' => $text,
            'source' => 'wp2tsina',
        );
        
        if (!!$media) {
		    // 保存远程图片到本地
            if (preg_match('/^https?:\/\//', $media)) {
                $tmpfname = tempnam("/tmp", "twpic_");
                $f = fopen($tmpfname, "w");
                fwrite($f, file_get_contents($media));
                fclose($f);
                
                $media = $tmpfname;
            }elseif (preg_match('/^file:\/\//', $media)) {
                $media = str_replace('file://', '', $media);
            }
            
            $this->agent->_submit_type = "multipart/form-data";
            
            if (file_exists($media)) {
                $this->agent->submit($api, $pars, array('media' => $media));
                @unlink($media);
            }else {
                $this->agent->submit($api, $pars);
            }
        }else {
            $this->agent->submit($api, $pars);
        }
        
        return $this->__response2array($this->agent->results);
    }
    
    function __response2array($results = null)
    {
        if (empty($results)) return false;
        return json_decode($results, true);
    }
}

?>
